package study.dq.unit.test.until;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DruidConnection {
    private static Properties properties = null;
    private static DataSource dataSource = null;
    private static volatile DruidConnection druidConnection = null;
    static {
        try {
            properties = new Properties();
            InputStream is = DruidConnection.class.getClassLoader().getResourceAsStream("druid.properties");
            properties.load(is);
            dataSource = getDataSource();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private DruidConnection(){}

    public static DruidConnection getInstance(){
        if (druidConnection ==null){
            synchronized (DruidConnection.class){
                if (druidConnection ==null){
                    druidConnection = new DruidConnection();
                }
            }
        }
        return druidConnection;
    }

    public DataSource getDatasource(){
        return dataSource;
    }


    public Connection getConnect(){
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    private static DataSource getDataSource(){
        DataSource dataSource = null;
        try {
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataSource;
    }


}
